
/***
 *  http serve
 */

const querystring = require("querystring");
const http = require("http");
const fs = require("fs");
const url = require("url");
const game = require("./game");

let playerWon = 0;
let playerLastAction = null;
let sameCount = 0;

http.createServer((request, response) => {

    const parseUrl = url.parse(request.url);
    console.log(parseUrl)

    if (parseUrl.pathname == '/favicon.icon') {
        response.writeHead(200);
        response.end();
        return;
    }

    if (parseUrl.pathname == '/game') {
        const query = querystring.parse(parseUrl.query);
        const playAction = query.action;
        const gameResult = game(playAction);

        if (playerWon >= 3) {
            response.writeHead(500);
            response.end('不玩了，弱爆了！')
        }

        if (playerLastAction && playAction === playerLastAction) {
            sameCount++;
        } else {
            sameCount = 0;
        };
        playerLastAction = playAction;

        if (sameCount >= 3) {
            response.writeHead(400);
            response.end('不玩了，你舞弊！');
            return;
        }

        if (gameResult === 0) {
            response.end('平局');
        } else if (gameResult === 1) {
            playerWon++
            response.end('yeah 你赢了');
        } else {
            response.end('cry 你输了');
        }
    }

    if (parseUrl.pathname == '/') {
        console.log(response)
        fs.createReadStream(__dirname + '/index.html')
            .pipe(response)
    }

}).listen(3001);


